package com.zzx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzx.domain.LoginUser;
import com.zzx.domain.Manager;
import com.zzx.domain.Permission;
import com.zzx.domain.Role;
import com.zzx.service.ManagerService;
import com.zzx.service.PermissionService;
import com.zzx.service.RoleService;
import com.zzx.util.FiexdValue;
import com.zzx.util.JwtUtil;
import com.zzx.util.SecurityContextHolderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserDetailsServerImpl implements UserDetailsService {
    @Autowired
    private ManagerService managerService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<Manager> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Manager::getMgName,username);
        wrapper.eq(Manager::getMgState, FiexdValue.UNDISABLE);
        Manager one = managerService.getOne(wrapper);
        /*如果为空则直接返回错误信息*/
        if(Objects.isNull(one)){
             throw new RuntimeException("用户名不存在或者用户被禁用");
        }
        //        /*返回LoginUser对象*/

        /* TODO 设置权限*/
        //获取当前绝对所有权限名称
        /*获取角色中的所有权限你*/
        Role role = roleService.getById(one.getRoleId());
        String[] split = role.getPsIds().split(",");
        /*获取权限名称*/
        LambdaQueryWrapper<Permission> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(Permission::getPsId,split);
        List<Permission> list = permissionService.list(wrapper1);

        List<String> collect = list.stream().map(item -> item.getPsName()).collect(Collectors.toList());
        LoginUser loginUser = new LoginUser(one,collect);

        return loginUser;
    }
}
